const util = require('../../../utils/util.js')
const { getTimeTable, findIntentNoticeDetail } = require('../../../api/geData.js')
const app = getApp();
let dayscount = 30;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    dayCover: true,
    dayDate: {},
    loadingBool: false,
    canClickBool: true,
    classsituation:"0",
    isShade:true,
    tcjsTime:'',
    tcksTime:'',
    weekData: [{
      week: 0,
      day: '日',
      time: {
        top: false,
        middle: false,
        bottom: false
      }
    },
    {
        week: 1,
        day: '一',
        time: {
          top: false,
          middle: false,
          bottom: false
        }
      },
      {
        week: 2,
        day: '二',
        time: {
          top: false,
          middle: false,
          bottom: false
        }
      },
      {
        week: 3,
        day: '三',
        time: {
          top: false,
          middle: false,
          bottom: false
        }
      },
      {
        week: 4,
        day: '四',
        time: {
          top: false,
          middle: false,
          bottom: false
        }
      },
      {
        week: 5,
        day: '五',
        time: {
          top: false,
          middle: false,
          bottom: false
        }
      },
      {
        week: 6,
        day: '六',
        time: {
          top: false,
          middle: false,
          bottom: false
        }
      }
    ],
    chooseArr: [],
    isCover: true,
    courseData: {},
    btnChangeColor: null,
    nowChooseArr: [],
    isChange: false,
    // 选择空闲时间上课时间
    schoolTime: [{
      text: '上：上课时间9:30-12:00',
      color: 'orange'
    }, {
      text: '下：上课时间14:30-17:00',
      color: 'rose'
    }, {
      text: '晚：上课时间19:00-21:30',
      color: 'blue'
    },{
        text: '实际上课时间以班主任通知为准',
        color: 'lightBlue'
      }
    // , {
    //   text: '全选为全天',
    //   color: 'skyBlue'
    // }
    ],
    isJobCourse: null,
    jobCheckNum: {
      now: 0,
      former: 0
    },
    jobCheckTotal: 0

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let passData = wx.getStorageSync('passData'),
      passStartDate = passData.startTime.split('-'),
      passEndDate = passData.endTime.split('-'),
      that = this
    // console.log(options)
    if(options.classsituation=='1')
    {
      this.setData({
        btnChangeColor:true
      })
    }
    this.setData({
      courseData: passData,
      nowChooseArr: this.data.weekData,
      isJobCourse: passData.isJobCourse,
      isCover: options.showQuick != '1',
      classsituation:options.classsituation,
      isShade: options.showQuick != '1',
      tcksTime: passData.startTime,
      tcjsTime: passData.endTime
    })

    let startDate = {
      year: passStartDate[0],
      month: passStartDate[1] - 1,
      day: passStartDate[2]
    };
    let endDate = {
      year: passEndDate[0],
      month: passEndDate[1] - 1,
      day: passEndDate[2]
    };

    intDate(this, startDate, endDate, passData.isJobCourse,options.classsituation);

    // 是就业课程的时候
    if (passData.isJobCourse){
      findIntentNoticeDetail(passData.noticeId).then(res => {
        let data = res.detailList
        that.setData({
          jobCheckTotal: res.map.course_time_sum
        })
        that.jobCourseTime(data)
      })
    }
  },
  jobCourseTime(courseTime){
    let dates = this.data.dates
    dates.map(item =>{
      item.map(val => {
        courseTime.map(msg =>{
          let stamp = new Date(val.date).getTime()
          if (stamp == msg.date){
            // console.log(msg.date)
            // console.log(val.date)
            val.inDate = true
            val.jobCourseTime[util.formatDateDtate(msg.shift)] = true
          }
        })
      })
    })

    // console.log(dates)
    this.setData({
      dates
    })
  },



  toQuickChoice() {
    // console.log(this.data.weekData)
    this.setData({
      isCover: false,
      isChange: false,
      nowChooseArr: this.data.weekData
    })
  },
  // 正常选择关闭
  closeFn() {
    this.setData({
      isCover: true,
      weekData: this.data.nowChooseArr
    })
  },
  // 脱产确定按钮
  btnRealease(){
    this.setData({
      isShade:true
    })
  },
  // 周快速选择时间
  chooseTimeFn(e) {
    let week = e.currentTarget.dataset.week,
      time = e.currentTarget.dataset.time,
      chooseArr = this.data.chooseArr,
      weekData = this.data.weekData,
      idx = e.currentTarget.dataset.index,
      day = weekData[idx].day,
      nowChooseArr = this.data.nowChooseArr,
      chooseArrBool = []

    weekData[idx].time[time] = !weekData[idx].time[time]
    weekData.map((item, index) => {
      if (item.time.top != nowChooseArr[index].time.top || item.time.middle != nowChooseArr[index].time.middle || item.time.bottom != nowChooseArr[index].time.bottom){
        chooseArrBool[index] = true
      } else {
        chooseArrBool[index] = false
      }


      if (item.time.top || item.time.middle || item.time.bottom) {
        if (chooseArr.indexOf(item.day) == -1) {
          chooseArr.push(day)
        }
      } else {
        chooseArr.forEach((val, index) => {
          if (val == item.day) {
            chooseArr.splice(index, 1)
          }
        })
      }
    })

    if (chooseArrBool.indexOf(true) != -1 || this.data.chooseArr.length == 0){
      this.setData({
        isChange: true
      })
    } else {
      this.setData({
        isChange: false
      })
    }

    if (this.data.chooseArr.length == 0){
      this.setData({
        isChange: false
      })
    }

    this.setData({
      weekData: weekData,
      chooseArr: chooseArr
    })
  },
  btnSave() {
    if (!this.data.isChange) return
    let weekData = this.data.weekData
    this.quickChoice(weekData)
    this.setData({
      isCover: true,
      nowChooseArr: weekData
    })
  },
  quickChoice(eventDetail) {
    let dates = this.data.dates;
    let weekChoose = eventDetail;
    let btnChangeColor = false;
    // console.log(dates)
    // console.log(weekChoose)
    dates.forEach((date) => {
      date.map((el, index) => {
        weekChoose.map((el1, index1) => {
          if (el.week == el1.week) {
            el.orderTime = el1.time
          }
        })
        if (el.orderTime.top || el.orderTime.middle || el.orderTime.bottom) {
          btnChangeColor = true
        }
      })
    })
    this.setData({
      dates: dates,
      btnChangeColor: btnChangeColor
    });
  },
  // 天快速选择时间
  toChooseDay(e) {
    let checkDay = e.currentTarget.dataset.checkDay,
      jobCheckNum = this.data.jobCheckNum,
      dates = this.data.dates

    // console.log(dates)
    // console.log(checkDay)
    
    jobCheckNum.former = jobCheckNum.now

    if (!checkDay.jobCourseTime.top && !checkDay.jobCourseTime.middle && !checkDay.jobCourseTime.bottom) return

    dates.map(item => {
      item.map(val =>{
        val.isClick = false
        if (checkDay.date == val.date){
          val.isClick = true
        }
      })
    })

    this.setData({
      dayCover: false,
      dayDate: checkDay,
      jobCheckNum: jobCheckNum
    })
  },
  dayChooseTime(e) {
    let dayDate = this.data.dayDate,
      text = e.target.dataset.text,
      jobCheckNum = this.data.jobCheckNum
    dayDate.orderTime[text] = !dayDate.orderTime[text]
    dayDate.orderTime[text] && (jobCheckNum.now++ , true) || jobCheckNum.now --
    // console.log(jobCheckNum.former)
    this.setData({
      dayDate: dayDate,
      jobCheckNum: jobCheckNum
    })
  },
  sureChoose() {
    let dayDate = this.data.dayDate
    this.chooseDay(dayDate)
    this.setData({
      dayCover: true
    })
  },
  chooseDay(checkDay) {
    // let checkMonth = e.currentTarget.dataset.whichMonth;
    let dates = this.data.dates;
    let btnChangeColor = false;
    let weekData = this.data.weekData;
    weekData.forEach(item => {
      if (item.week == checkDay.week) {
        item.time = checkDay.orderTime
      }
    })

    dates.forEach(val => {
      val.map(item => {
        if (item.date == checkDay.date) {
          item.orderTime = checkDay.orderTime
          item.choosed = (item.orderTime.top || item.orderTime.middle || item.orderTime.bottom)
        }
        if (item.orderTime.top || item.orderTime.middle || item.orderTime.bottom) {
          btnChangeColor = true
        }
      })
    })
    this.setData({
      dates: dates,
      btnChangeColor: btnChangeColor,
      weekData: weekData
    });

  },
  closeCover(){
    let jobCheckNum = this.data.jobCheckNum
    jobCheckNum.now = jobCheckNum.former
    this.setData({
      dayCover: true,
      jobCheckNum: jobCheckNum
    })
  },
  // 清除所有函数
  clearAll(){
    let that = this
   wx.showModal({
     title: '',
     content: '确认清空当前所有选择吗？',
     contentColor: 'red',
     confirmColor: '#2A8EFF',
     success(res){
       if (res.confirm) {
         let weekData = that.data.weekData,
           dates = that.data.dates

         weekData.map(item => {
           item.time.bottom = item.time.top = item.time.middle = false
         })

         dates.map(item => {
           item.map(val => {
             val.orderTime.top = val.orderTime.middle = val.orderTime.bottom = val.isClick= false
           })
         })
         that.setData({
           weekData: weekData,
           dates: dates,
           btnChangeColor: false
         })
       }
       
     }
   })
    
  },

  disagreeTime(){
    // console.log(this.data.courseData)
    util.disagreeFn(this.data.courseData.courseId)
  },

  btnSubmit(e) {

    if (!this.data.canClickBool) return
    if (this.data.isJobCourse){
      // console.log('这里是6666')
      this.data.jobCheckNum.now * 1 >= this.data.jobCheckTotal && this.sendDataFn(e)
    } else {
      // console.log('这里是9999')
      this.data.btnChangeColor && this.sendDataFn(e)
    }
  },
  sendDataFn(e){
    let sendDate = [], // 处理数据要发送给后台的数据
      that = this
    this.setData({
      loadingBool: true,
      canClickBool: false
    })
    this.data.dates.forEach(item => {
      item.forEach(val => {
        if (val.inDate) {
          for (let key in val.orderTime) {
            if (val.orderTime[key]) {
              let date = {},
                formatNumber = [],
                time = {
                  top: '早',
                  middle: '中',
                  bottom: '晚'
                }
              date.stuid = wx.getStorageSync('userInfo').cluesOrStuId
              date.state = time[key]
              // 转化日期对象 把/转化成 -
              val.date.split('/').forEach(item => {
                formatNumber.push(util.formatNumber(item))
              })
              date.studate = formatNumber.join('-')
              date.courseid = wx.getStorageSync('passData').courseId
              date.noticid = wx.getStorageSync('passData').noticeId
              sendDate.push(date)
            }
          }
        }
      })

    })

    wx.request({
      url: app.globalData.baseUrl + '/calendars/calendars',
      data: {
        "calendars": sendDate,
      },
      method: 'POST',
      header: {
        "Content-Type": "application/json"
      },
      success(res) {
        if (res.data.code == 0) {
          util.sendForm(e.detail.formId, '8yXiZLs675d1hmlWll80ViClYX0vapyJWN6QrNRqZ68', '2', wx.getStorageSync('passData').courseId, wx.getStorageSync('passData').packId)
          wx.reLaunch({
            url: '/pages/detail/waitGrade/waitGrade?showTextIndex=0&showBtn=1',
          })
          that.setData({
            loadingBool: false,
            canClickBool: true
          })
        }
      }
    })
  }
});

function intDate(self, fromDay, toDay, isJobCourse,classsituation) {
  let platform; //手机操作系统
  wx.getSystemInfo({
    success: function(res) {
      // console.log(res)
      // console.log(res.platform)
      platform = res.platform;
    }
  })
  let nowYear = fromDay.year,
    nowMonth = fromDay.month,
    today = fromDay.day,
    nowTimeStamp = new Date(nowYear, nowMonth, today).getTime() // 课程时间段 开始时间的时间戳 用于后面的比较

  let endDate = new Date(toDay.year, toDay.month, toDay.day),
    endYM = new Date(endDate.getFullYear(), endDate.getMonth()),
    endTimeStamp = endDate.getTime() // 课程时间段 结束时间的时间戳 用于后面的比较

  let dates = [];
  for (let i = nowMonth; new Date(nowYear, i) <= endYM; i++) {
    let item = [];
    let monthDays = new Date(nowYear, i + 1, 0).getDate(); //获取该月天数  +1
    for (let j = 1; j <= monthDays; j++) {
      let _year = new Date(nowYear, i).getFullYear(),
        // _month = new Date(nowYear, i).getMonth(); //获取该月月份 +1
        _month = new Date(nowYear, i).getMonth() + 1; //获取该月月份 +1
      let day = _year + '/' + _month + '/' + j,
        inDate = `${_year}-${_month}-${j}`,
        oDate = {}
      if (platform == 'ios') {
        inDate = `${_year}/${_month}/${j}`
      }
      oDate.week = new Date(inDate).getDay()
      if (isJobCourse) {
        oDate.jobCourseTime = {
          top: false,
          middle: false,
          bottom: false
        }
      } else {
        oDate.jobCourseTime = {
          top: true,
          middle: true,
          bottom: true
        }
      }
      if(classsituation=='1')
      {
        oDate.orderTime = {
          top: true,
          middle: true,
          bottom: true
        }
      }else
      {
        oDate.orderTime = {
          top: false,
          middle: false,
          bottom: false
        }
      }
      
      oDate.date = day.toString()
      oDate.choosed = false
      oDate.inDate = false
      oDate.isClick = false

      // 筛选出时间段  用inDate 标记  用时间戳来比较
      if (!isJobCourse){ // 不是就业课程的
        if (new Date(inDate).getTime() >= nowTimeStamp && new Date(inDate).getTime() <= endTimeStamp) {
          oDate.inDate = true
        }
      }
      
      item.push(oDate)
    }
    dates.push(item);
  }
  let startDay = `${nowYear}/${nowMonth + 1}/${today}`,
    endDay = `${endDate.getFullYear()}/${endDate.getMonth() + 1}/${endDate.getDate()}`;
  // console.log(dates)
  self.setData({
    dates,
    startDay,
    endDay
  })
}